using System;
using System.Collections.Specialized;
using System.Linq;
using Microsoft.Practices.Composite.Presentation.Regions;
using PrismNavigationFramework.Navigation;
using PrismNavigationFramework.Navigation.Controls;

namespace PrismNavigationFramework.RegionBehaviors
{
    public class PrismNavigationSecondaryFrameRegionBehavior : RegionBehavior
    {
        private readonly IPrismViewLoadingService _prismViewLoadingService;
        private readonly IPrismNavigationConfiguration _prismNavigationConfiguration;

        public const string BehaviorKey = "PrismNavigationSecondaryFrameRegionBehavior";

        public PrismNavigationSecondaryFrame HostFrame { get; set; }


        public PrismNavigationSecondaryFrameRegionBehavior(IPrismViewLoadingService prismViewLoadingService, IPrismNavigationConfiguration prismNavigationConfiguration)
        {
            _prismViewLoadingService = prismViewLoadingService;
            _prismNavigationConfiguration = prismNavigationConfiguration;
        }

        protected override void OnAttach()
        {
            if (this.HostFrame == null)
            {
                throw new InvalidOperationException("No HostFrame defined in region.");
            }

            this.Region.ActiveViews.CollectionChanged += this.OnActiveViewsChanged;

            var regionName = this.HostFrame.GetValue(RegionManager.RegionNameProperty) as string;
            if (!string.IsNullOrEmpty(regionName))
            {
                this.HostFrame.Name = regionName;
            }
        }

        private void OnActiveViewsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            var views = this.Region.ActiveViews.ToList();
            this.HostFrame.Items.Clear();
            foreach (var view in views)
            {
                if (!this.HostFrame.Items.Contains(view))
                {
                    this.HostFrame.Items.Add(view);
                }
            }           
        }        
    }
}